package com.hujifang.elasticsearch.service.utils;

import com.hujifang.elasticsearch.utils.DateUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 查询条件工具<br/>
 * Created by Hurricane.Hu on 2018/5/20.
 */
public class SearchConditionUtil {

    private static final Logger LOGGER= LoggerFactory.getLogger(SearchConditionUtil.class);

    public static Map<String,List<String>> getRangeByStr(String rangeCondition){
        Map<String,List<String>> rangeMap=new HashMap<>();
        if(StringUtils.isNotBlank(rangeCondition)){
            String[] conditions = rangeCondition.split("&");
            String patternString = "^([a-zA-z_$]+)([<>]?=?)([\\w-]+)$";
            Pattern pattern = Pattern.compile(patternString);
            for (String condition: conditions) {
                if (StringUtils.isNotBlank(condition)) {
                    Matcher mat = pattern.matcher(condition);
                    if(mat.find() && mat.groupCount()==3){
                        List<String> rangeList=new ArrayList<>();
                        rangeList.add(mat.group(1));
                        rangeList.add(mat.group(2));
                        rangeList.add(mat.group(3));
                        rangeMap.put(mat.group(0),rangeList);
                    }
                }
            }
        }
        return rangeMap;
    }


    /**
     * 检查是否是有效的日期格式
     * @param dateStr
     * @author HuJiFang
     */
    public static boolean checkValidDate(String dateStr) {
        boolean flag=false;
        try {
            Pattern p = Pattern.compile("(\\d{1,4}[-|\\/|年|\\.]\\d{1,2}[-|\\/|月|\\.]\\d{1,2}([日|号])?(\\s)*(\\d{1,2}([点|时])?((:)?\\d{1,2}(分)?((:)?\\d{1,2}(秒)?)?)?)?(\\s)*(PM|AM)?)",
                    Pattern.CASE_INSENSITIVE|Pattern.MULTILINE);
            Matcher matcher = p.matcher(dateStr);
            if (matcher.find() && matcher.groupCount() >= 1) {
                flag=true;
            }
        } catch (Exception e) {
            LOGGER.warn(e.getMessage(),e);
        }
        return flag;
    }

    /**
     * 获取当天的最后一秒
     * @param date
     * @author HuJiFang
     */
    public static Date getDayLastTime(Date date) {
        Date resultDate= null;
        if(date!=null){
            try {
                String dataStr= DateUtil.dateToString(date);
                Date newDate=DateUtil.getDateByFormatStr(dataStr,"yyyy-MM-dd");
                int dayMis=1000*60*60*24;
                long curMillisecond=newDate.getTime();
                long resultMis=curMillisecond+(dayMis-1);
                resultDate = DateUtil.toDate(resultMis);
            } catch (Exception e) {
                LOGGER.warn(e.getMessage(),e);
            }
        }
        return resultDate;
    }
}
